<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card 内容区 -->
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 减0进行字符串的转换-->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签 -->
      <el-form
        :label-position="'top'"
        :model="addForm"
        status-icon
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-tabs
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
          v-model="activeIndex"
          :tab-position="'left'"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item type="number" label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item type="number" label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item type="number" label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="catelist"
                :props="cateProps"
                @change="CatChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  :label="cb"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传 -->
            <el-upload
              :headers="headerObj"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"> </quill-editor>
            <el-button class="Addbtn" @click="btnAdd" type="primary"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->

    <el-dialog title="图片预览" :visible.sync="preImgdialogVisible" width="50%">
      <img :src="prewPath" alt="" class="prewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: '0',
      // 商品分类列表
      catelist: [],
      // 商品添加的表单数据
      addForm: {
        goods_name: '',
        goods_price: 1,
        goods_weight: 1,
        goods_number: 1,
        // 商品分类id
        goods_cat: [],
        //图片路径 服务器返回的
        pics: [],
        goods_introduce: '',
        // attrs 放的是manyTableData 和onlyTableData 处理后的部分项 提交给后端
        attrs: [],
      },
      addFormRules: {
        goods_name: [
          {
            required: true,
            message: '必填项',
            trigger: 'blur',
          },
        ],
        goods_price: [
          {
            required: true,
            message: '必填项',
            trigger: 'blur',
          },
        ],
        goods_weight: [
          {
            required: true,
            message: '必填项',
            trigger: 'blur',
          },
        ],
        goods_number: [
          {
            required: true,
            message: '必填项',
            trigger: 'blur',
          },
        ],
      },
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },

      //动态参数的数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 图片上传的地址
      uploadUrl: 'http://127.0.0.8:8888/api/private/v1/upload', // 请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      // 完整路径 预览用 对话框
      prewPath: '',
      preImgdialogVisible: false,
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    },
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取商品分类列表失败')
      // this.$message.success('获取商品分类列表成功')
      this.catelist = res.data
      // console.log(res.data);
    },
    //级联选择器值变化时调用
    CatChange() {
      console.log(this.addForm.goods_cat)
      //控制只允许选中三级
      // 长度不为3清空数组即可
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 页签跳转之前
    beforeTabLeave(activeName, oldActiveName) {
      //  return false 阻止跳转
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // tabs页签被点击
    async tabClicked() {
      console.log(this.activeIndex)
      // 商品参数
      if (this.activeIndex === '1') {
        // 获取商品参数数据
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'many',
            },
          }
        )

        if (res.meta.status !== 200) return this.$message.error('参数列表失败')

        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
        })
        this.manyTableData = res.data
        console.log(res.data)
      } else if (this.activeIndex === '2') {
        // 获取静态属性数据
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'only',
            },
          }
        )

        if (res.meta.status !== 200) return this.$message.error('静态失败')

        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    // 图片预览
    handlePreview(file) {
      console.log(file)
      this.prewPath = file.response.data.url
      this.preImgdialogVisible = true
    },
    // 图片删除
    handleRemove(file) {
      console.log(file)
      // 1,获取到图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2,找到索引
      const i = this.addForm.pics.findIndex((item) => {
        item.pic === filePath
      })
      // 3,从数组中删除
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm)
    },
    // 图片上传成功
    handleSuccess(response) {
      console.log(111)
      const infoObj = {
        pic: response.data.tmp_path,
      }
      this.addForm.pics.push(infoObj)
      console.log(this.addForm)
    },
    //shangpingtianjia
    btnAdd() {
      console.log(this.addForm)
      //  预校验
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        // 执行添加的业务逻辑
        // 1，处理数据格式，以使其符合接口需要
        // 1，goods_cat 数组-》字符串
        // 因为goods_cat和级联选择器双向绑定（必须是数组），所以使用loads方法深拷贝一个对象，我们操作该对象即可。
        // lodash cloneDeep(obj)
        const form = _.cloneDeep(this.addForm)
        // join返回一个新数组   join() 方法不会改变原始数组。
        form.goods_cat = form.goods_cat.join(',')
        console.log(form)
        // 处理 静态属性和动态参数数据
        this.manyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            // join() 方法不会改变原始数组。
            attr_value: item.attr_vals.join(','),
          }
          // console.log(this.addForm.attrs)
          this.addForm.attrs.push(newInfo)
        })
        this.onlyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            // join() 方法不会改变原始数组。
            attr_value: item.attr_vals,
          }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        console.log(form)
        // 发起请求 添加商品
        // 商品名称 唯一
        const {data:res}=await this.$http.post('goods',form)
        console.log(res);
        if(res.meta.status!==201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    },
  },
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 15px 0 0 !important;
}

.prewImg {
  width: 100%;
}

.Addbtn {
  margin-top: 10px;
}
</style>
